package com.whosly.strategy.registrar;

import com.whosly.strategy.annotation.EnableStrategy;
import com.whosly.strategy.registrar.container.IBeanDefinitionRegistrar;
import com.whosly.strategy.util.LoggerUtil;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StopWatch;

import java.util.*;

/**
 * 抽象 BeanDefinitionRegistrar
 *
 * @Author yueny09 <deep_blue_yang@126.com>
 * @Date 2019-09-04 14:22
 */
public abstract class AbstractBeanDefinitionRegistrar implements IBeanDefinitionRegistrar {
    /**  */
    protected static final String BASE_PACKAGES = "com.whosly";

    protected String getTaskName(){
        return "ContainerRegistrar";
    }

    /**
     * AnnotationMetadata参数用来获得当前配置类上的注解； BeanDefinittionRegistry参数用来注册Bean
     *
     * @param importingClassMetadata
     * @param registry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                        BeanDefinitionRegistry registry) {
        StopWatch stopWatch = null;

        /* 获取注解配置 */
        AnnotationAttributes enableStrategy =
                AnnotationAttributes.fromMap(
                        importingClassMetadata.getAnnotationAttributes(EnableStrategy.class.getName(), false));
        if(enableStrategy.getBoolean("performance")){
            stopWatch = new StopWatch(UUID.randomUUID().toString());
            stopWatch.start(getTaskName());
        }


        registerBeanDefinitions(enableStrategy, registry);


        if(stopWatch != null){
            stopWatch.stop();
            LoggerUtil.get(getClass()).info("{} 注册完成. 初始化耗时占用: {} ms, {}",
                    getTaskName(), stopWatch.getTotalTimeMillis(), stopWatch.prettyPrint());
        }else{
            LoggerUtil.get(getClass()).debug("{} 注册完成.", getTaskName());
        }
    }

    protected abstract void registerBeanDefinitions(AnnotationAttributes enableStrategy, BeanDefinitionRegistry registry);

}
